package com.ruoyi.common.utils;

import com.baidu.aip.ocr.AipOcr;
import org.json.JSONObject;
import org.springframework.stereotype.Component;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

@Component
public class BaiduOcrUtils {
    private static final Logger log = LoggerFactory.getLogger(BaiduOcrUtils.class);
    
    // 设置APPID/AK/SK
    private static final String APP_ID = "118287512";
    private static final String API_KEY = "yreCnz3UcMlVdBphnfYDSWOH";
    private static final String SECRET_KEY = "9mTAJ6mxDMaOf73WeDR0qlOUFKyXD8oo";

    private static AipOcr client;
    private static final int MAX_RETRIES = 3;
    private static final long RETRY_DELAY_MS = 1000;

    static {
        // 初始化AipOcr
        client = new AipOcr(APP_ID, API_KEY, SECRET_KEY);
        // 可选：设置网络连接参数
        client.setConnectionTimeoutInMillis(5000);
        client.setSocketTimeoutInMillis(60000);
    }

    /**
     * 身份证识别
     * @param image 图片base64字符串
     * @param idCardSide 身份证正反面（front/back）
     * @return 识别结果
     */
    public static JSONObject idCardRecognition(String image, String idCardSide) {
        if (image == null || image.trim().isEmpty()) {
            throw new IllegalArgumentException("图片数据不能为空");
        }

        int retryCount = 0;
        Exception lastException = null;

        while (retryCount < MAX_RETRIES) {
            try {
                // 传入可选参数
                HashMap<String, String> options = new HashMap<>();
                options.put("detect_direction", "true");
                options.put("detect_risk", "true");
                options.put("id_card_side", idCardSide);

                // 调用接口
                JSONObject result = client.idcard(image, idCardSide, options);
                
                // 检查结果
                if (result.has("error_code")) {
                    Object errorCode = result.get("error_code");
                    boolean hasError = false;
                    String errorMsg = "";
                    
                    if (errorCode instanceof Integer) {
                        int intErrorCode = (Integer) errorCode;
                        hasError = intErrorCode != 0;
                        if (hasError) {
                            errorMsg = result.getString("error_msg");
                            log.error("百度OCR识别失败，错误码：{}，错误信息：{}", intErrorCode, errorMsg);
                        }
                    } else if (errorCode instanceof String) {
                        String strErrorCode = (String) errorCode;
                        hasError = !("0".equals(strErrorCode) || "0.0".equals(strErrorCode));
                        if (hasError) {
                            errorMsg = result.getString("error_msg");
                            log.error("百度OCR识别失败，错误码(字符串)：{}，错误信息：{}", strErrorCode, errorMsg);
                        }
                    } else {
                        log.warn("未知的 error_code 类型: " + errorCode.getClass().getName());
                    }
                    
                    if (hasError) {
                        throw new RuntimeException("百度OCR识别失败：" + errorMsg);
                    }
                }
                
                return result;
            } catch (Exception e) {
                lastException = e;
                retryCount++;
                if (retryCount < MAX_RETRIES) {
                    log.warn("OCR识别失败，第{}次重试", retryCount);
                    try {
                        TimeUnit.MILLISECONDS.sleep(RETRY_DELAY_MS);
                    } catch (InterruptedException ie) {
                        Thread.currentThread().interrupt();
                    }
                }
            }
        }

        log.error("OCR识别失败，已重试{}次", MAX_RETRIES, lastException);
        throw new RuntimeException("OCR识别失败，请稍后重试", lastException);
    }

    /**
     * 护照识别
     * @param image 图片base64字符串
     * @return 识别结果
     */
    public static JSONObject passportRecognition(String image) {
        if (image == null || image.trim().isEmpty()) {
            throw new IllegalArgumentException("图片数据不能为空");
        }

        int retryCount = 0;
        Exception lastException = null;

        while (retryCount < MAX_RETRIES) {
            try {
                // 传入可选参数
                HashMap<String, String> options = new HashMap<>();
                options.put("detect_direction", "true");

                // 调用接口
                JSONObject result = client.passport(image, options);
                
                // 检查结果
                if (result.has("error_code")) {
                    Object errorCode = result.get("error_code");
                    boolean hasError = false;
                    String errorMsg = "";
                    
                    if (errorCode instanceof Integer) {
                        int intErrorCode = (Integer) errorCode;
                        hasError = intErrorCode != 0;
                        if (hasError) {
                            errorMsg = result.getString("error_msg");
                            log.error("百度OCR识别失败，错误码：{}，错误信息：{}", intErrorCode, errorMsg);
                        }
                    } else if (errorCode instanceof String) {
                        String strErrorCode = (String) errorCode;
                        hasError = !("0".equals(strErrorCode) || "0.0".equals(strErrorCode));
                        if (hasError) {
                            errorMsg = result.getString("error_msg");
                            log.error("百度OCR识别失败，错误码(字符串)：{}，错误信息：{}", strErrorCode, errorMsg);
                        }
                    } else {
                        log.warn("未知的 error_code 类型: " + errorCode.getClass().getName());
                    }
                    
                    if (hasError) {
                        throw new RuntimeException("百度OCR识别失败：" + errorMsg);
                    }
                }
                
                return result;
            } catch (Exception e) {
                lastException = e;
                retryCount++;
                if (retryCount < MAX_RETRIES) {
                    log.warn("OCR识别失败，第{}次重试", retryCount);
                    try {
                        TimeUnit.MILLISECONDS.sleep(RETRY_DELAY_MS);
                    } catch (InterruptedException ie) {
                        Thread.currentThread().interrupt();
                    }
                }
            }
        }

        log.error("OCR识别失败，已重试{}次", MAX_RETRIES, lastException);
        throw new RuntimeException("OCR识别失败，请稍后重试", lastException);
    }
} 